/*
 * @Author: JYJ 
 * @Date: 2020-07-11 22:08:00 
 * @Desc: 对话框管理
 */
namespace gf {
    export class DialogMgr extends gf.BaseClass {
        private _dlgs: any;
        public constructor() {
            super();
            this._dlgs = {};
        }
        public static getInstance(): DialogMgr {
            return super.getInstance();
        }
        /**
         * 显示对话框
         * @type cls 对话框类
         * @type layer 对话框层级,应该从LayerMgr获取
         */
        public async showDialog(dlgSetting: DialogSetting) {
            let dlg: gf.BaseDialog = this.getDlg(dlgSetting.dlgCls);
            if (null == dlg) {
                Log.log(`创建对话框 ${dlgSetting.dlgCls.name}`);
                dlg = new dlgSetting.dlgCls();
                this.cacheDlg(dlgSetting.dlgCls, dlg);
                await fairygui.UIPackage.loadPackage(dlgSetting.packageName);
                let root = fairygui.UIPackage.createObject(dlgSetting.packageName, dlgSetting.dlgComName).asCom;
                root.setSize(fairygui.GRoot.inst.width, fairygui.GRoot.inst.height);
                root.sortingOrder = dlgSetting.layer;
                fairygui.GRoot.inst.addChild(root);
                dlg.root = root;
                dlg.onInit.apply(dlg);
            }
            if (dlg.isInit) {
                dlg.onResume.apply(dlg);
            }
        }
        public hideDialog(dlgSetting: DialogSetting) {
            //TODO 异步处理，对话框加载是异步的所以这里要处理
            let dlg: BaseDialog = this.getDlg(dlgSetting.dlgCls);
            if (null == dlg) return;
            fairygui.UIPackage.removePackage(dlgSetting.packageName);
            Log.log(`隐藏对话框 ${dlgSetting.dlgCls.name}`);
            dlg.onPause.apply(dlg);
            fairygui.GRoot.inst.removeChild(dlg.root);
        }
        public destroyDialog(dlgSetting: DialogSetting) {
            let dlg: BaseDialog = this.getDlg(dlgSetting.dlgCls);
            if (null == dlg) return;
            //先关闭再销毁
            this.hideDialog(dlgSetting);
            Log.log(`销毁对话框 ${dlgSetting.dlgCls.name}`);
            delete this._dlgs[dlgSetting.dlgCls];
            dlg.onDestroy.apply(dlg);
            fairygui.GRoot.inst.removeChild(dlg.root);
            dlg.root.dispose();
            dlg.root = null;
        }
        private getDlg(cls): BaseDialog {
            return this._dlgs[cls];
        }
        private cacheDlg(cls, dlg: BaseDialog) {
            this._dlgs[cls] = dlg;
        }
    }
}